package com.aerfafish.spider.neo4j.spider.service.impl;

import com.aerfafish.spider.neo4j.dao.Person;
import com.aerfafish.spider.neo4j.repository.PersonRepository;
import com.aerfafish.spider.neo4j.spider.service.PersonService;
import org.neo4j.driver.exceptions.TransientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author aerfafish
 * @date 2021/4/23 11:43 上午
 */

@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    PersonRepository personRepository;

    @Override
    public void save(Person person) throws Exception {
        save(person.getCode());
    }

    @Override
    public void save(String code) throws Exception {
        if (code == null) {
            throw new Exception("code is null");
        }

        try {
            personRepository.save(code);
        } catch (TransientException | InvalidDataAccessApiUsageException e) {
            try {
                personRepository.save(code);
            } catch (TransientException | InvalidDataAccessApiUsageException e0) {
                personRepository.save(code);
            }
        }

    }

    @Override
    public Person queryByPersonCode(String code) throws Exception {
        List<Person> people = null;
        try {
            people = personRepository.queryPersonByCode(code);
        } catch (TransientException | InvalidDataAccessApiUsageException e) {
            try {
                people = personRepository.queryPersonByCode(code);
            } catch (TransientException | InvalidDataAccessApiUsageException e0) {
                people = personRepository.queryPersonByCode(code);
            }
        }

        if (people != null && people.size() > 1) {
            throw new Exception("code: " + code + " person is repeated");
        }
        if (people == null) {
            return null;
        }
        return people.get(0);
    }
}
